package com.fitz.provider.config;

import com.fitz.annotation.RpcService;
import com.fitz.registry.InstanceInfo;
import com.fitz.registry.InstanceRegistry;
import com.fitz.registry.nacos.NacosRegistry;
import com.fitz.remote.server.ProviderServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

@Deprecated
public class ProviderInitializer implements ApplicationContextAware, InitializingBean {

    private final int serverPort;

    private final String registryAddress;

    private final String serviceName;

    private final byte serializerType;

    private ProviderServer providerServer;

    private HashMap<String,Object> handlerMap = new HashMap<>();

    public ProviderInitializer(String serviceName,int serverPort, String registryAddress,byte serializerType) {
        this.serviceName = serviceName;
        this.serverPort = serverPort;
        this.registryAddress = registryAddress;
        this.serializerType = serializerType;
        init();
    }

    public void init(){
        InstanceRegistry serviceRegistry = new NacosRegistry(registryAddress);
        InstanceInfo instance = new InstanceInfo();
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            instance.setHost(localhost.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        instance.setServiceName(serviceName);
        instance.setPort(serverPort);
        instance.setSerializerType(serializerType);
        instance.setHandlerMap(handlerMap);
        providerServer = new ProviderServer(serviceRegistry, instance,handlerMap);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String,Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class);
        if (serviceBeanMap != null && serviceBeanMap.size() > 0){
            for (Object serviceBean : serviceBeanMap.values()){
                String interfaceName = serviceBean.getClass().getInterfaces()[0].getName();
                handlerMap.put(interfaceName,serviceBean);
            }
        }
        //等handlerMap初始化之后再启动注册服务
        providerServer.start();
//        serviceRegistry.register(instance);
    }
}
